package flst.ipiweb.struts.action.administrateur;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import flst.ipiweb.proxy.ServiceAdministrateurProxy;
import flst.ipiweb.service.ServiceCrypto;
import flst.ipiweb.transverse.Administrateur;
import flst.ipiweb.transverse.IPIException;

public class UpdateAdminPostAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		//On récupère la session
		HttpSession session = request.getSession();
		if(session.getAttribute("login") == null)
		{
			return mapping.findForward("login");
		}
		
		//Récupération de l'administrateur depuis le formulaire
		AdminForm vAdminForm = (AdminForm) form;
		Administrateur admin = new Administrateur();
		admin.setIdUser(vAdminForm.getIdAdmin());
		admin.setNom(vAdminForm.getLastname());
		admin.setPrenom(vAdminForm.getFirstname());
		admin.setLoginUtilisateur(vAdminForm.getLogin());
		//Cryptage du mot de passe
		String password = new ServiceCrypto().encrypt(vAdminForm.getPassword());
		admin.setPassword(password);
		
		//Instanciation du service administrateur
		ServiceAdministrateurProxy sAdministrateur = new ServiceAdministrateurProxy((Boolean) session.getAttribute("isSuper"));

		//Mise à jour de l'administrateur
		try {
			
			sAdministrateur.updateAdministrateur(admin);
			//Message de succes
			session.setAttribute("success", "AdminSuccess.update");
			session.setAttribute("error", null);
			
		} catch (IPIException e) {
			//Message d'erreur
			session.setAttribute("success", null);
			session.setAttribute("error", e.getMessage());
			
			request.setAttribute("admin", admin);
			request.setAttribute("pageTitle", "admin.update.title");
			request.setAttribute("mainTitle", "admin.update.mainTitle");
			
			request.setAttribute("action", "/update-admin-post");
			HashMap<String, String> onglet = new HashMap<String, String>();
			onglet.put("administrateur", "active");
			request.setAttribute("onglet", onglet);
			return mapping.findForward("update_admin");
		}
		return mapping.findForward("list_admin");
	}
}
